package com.hyx.bookManager.service.impl;

import com.hyx.bookManager.domain.common.CommonResult;
import com.hyx.bookManager.domain.dto.CurrentUserCount;
import com.hyx.bookManager.mapper.UserMapper;
import com.hyx.bookManager.service.UserService;
import com.hyx.bookManager.utils.EmailUtil;
import com.hyx.bookManager.utils.RedisUtil;
import com.hyx.bookManager.utils.Snowflake;
import com.hyx.bookManager.utils.TokenUtil;
import com.nimbusds.jose.JOSEException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author 黄乙轩
 * @Date 2021/6/7 21:44
 * @Version 1.0
 **/

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    Snowflake snowflake;

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    EmailUtil emailUtil;

    private static final String str = "1234567890";

    @Override
    public CommonResult loginUser(String ammount, String password) {
        int userByAmmount = userMapper.getUserByAmmount(ammount, password);
        if (userByAmmount == 0) {
            return CommonResult.fail(null, "账号密码不匹配");
        } else if (userByAmmount == 1) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ammount);
            String token = null;
            try {
                token = tokenUtil.getTokenHS256(map);
            } catch (JOSEException e) {
                e.printStackTrace();
            }
            return CommonResult.success("登录成功", token);
        }
        return CommonResult.fail(null, "异常接口");
    }

    @Override
    public CommonResult registerUser(Integer Code, String name, String password, String email) {
        String code = redisUtil.getHash(email);
        if (!Integer.valueOf(code).equals(Code)) {
            return CommonResult.fail(null, "验证码错误");
        }
        int num = userMapper.getUserByEmail(email);
        if (num == 0) {
            LocalDateTime createTime = LocalDateTime.now();
            LocalDateTime updateTime = LocalDateTime.now();
            Long id = snowflake.nextId();
            userMapper.insertUser(name, password, email, id, createTime, updateTime);
            Integer roleId = 1;
            userMapper.insertUserRole(id,roleId,snowflake.nextId());
            return CommonResult.success("注册成功",id);
        } else if (num == 1) {
            return CommonResult.fail(null, "邮箱已重复");
        }
        return CommonResult.fail(null, "非法错误");
    }

    @Override
    public CommonResult getCode(String email) {
        Random random = new Random();
        String text = "";
        Integer len = 6;
        for (int i = 0; i < len; i++) {
            text+=str.charAt(Math.abs(random.nextInt(str.length())));
        }
        redisUtil.setHash(email,text,15*60*1000);
        try {
            emailUtil.sendCodeEmail(email,text);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.fail();
        } catch (MessagingException e) {
            e.printStackTrace();
            return CommonResult.fail();
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult getAllUser() {
        return CommonResult.success(userMapper.getAllUser());
    }

    @Override
    public CommonResult getCurrentUser() {
        LocalDate now = LocalDate.now();
        LocalDate before = now.minusDays(7);
        List<LocalDate> list = new ArrayList<>();
        for(int i=0;i<7;i++){
            list.add(before.plusDays(i));
        }
        List<Long> currentUser = userMapper.getCurrentUser(before, now);
        CurrentUserCount userCount = new CurrentUserCount();
        userCount.setNum(currentUser);
        userCount.setTime(list);
        return CommonResult.success(userCount);
    }


}
